package com.golang.api.interceptor;


import cn.hutool.core.util.ObjectUtil;
import com.golang.api.local.ThreadHelper;
import com.golang.api.redis.RedisCache;
import com.golang.api.redis.TokenService;
import com.golang.api.util.AbstractHandlerInterceptorAdapter;
import com.golang.api.util.RequestUtil;
import com.golang.api.util.Result;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截请求,进行token校验和验签
 */
@Component
public class TokenInterceptor extends AbstractHandlerInterceptorAdapter {

	private final Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
	
	@Autowired
	TokenService tokenService;
	
	@Autowired
	RedisCache redisCache;


    /**
     * 校验所有请求参数是否为 "" || null
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = RequestUtil.getRequestParam(request, "token");

		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}

		if ("".equals(token) || null == token) {
			super.responseErrorData(response, new Result<>(500, "token参数为空"));
			return false;
		}

//		String tokenValue=redisCache.getCacheObject(token);
		String tokenValue="123";
		if(ObjectUtil.isEmpty(tokenValue)){
			super.responseErrorData(response, new Result<>(500, "token不存在"));
			return false;
		}
		ThreadHelper.setUserId(tokenValue);
        return true;
    }



    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		ThreadHelper.removeUserId();
    }
}
